﻿Imports System.Drawing
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

Public Class CodeFrom

    Public dic1 As Dictionary(Of String, String) = New Dictionary(Of String, String)




    Private Sub PictureBox2_Click(sender As Object, e As EventArgs) Handles PictureBox2.Click
        PictureBox2.Visible = False
        ListBox1.Visible = False
        TextBox1.Text = ""
    End Sub

    Private Sub TextBox1_Click(sender As Object, e As EventArgs) Handles TextBox1.Click
        PictureBox2.Visible = True
        '/设置listbox可见性
        ListBox1.Left = TextBox1.Left
        ListBox1.Top = TextBox1.Top + TextBox1.Height
        ListBox1.Width = TextBox1.Width
        ListBox1.Height = TreeView1.Height + 5
        ListBox1.Visible = True

        '/
        Call RefreshListbox1()
    End Sub

    Private Sub TextBox1_GotFocus(sender As Object, e As EventArgs) Handles TextBox1.GotFocus
        Call RefreshListbox1()
    End Sub

    Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus

        PictureBox2.Visible = False
        'ListBox1.Items.Clear()
        'ListBox1.Visible = False

    End Sub


    Function GetPNode(nnode As TreeNode) As String
        Dim s As String
        Try
            s = nnode.Parent.Text
        Catch
            Return ""
        End Try
        Return s
    End Function
    Function GetPPNode(node As TreeNode) As String
        Dim s As String
        Try
            s = node.Parent.Parent.Text
        Catch
            Return ""
        End Try
        Return s
    End Function

    Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
        '选定treeview1节点后，在richtextbox中显示具体代码

        Dim ptxt As String = ""
        Dim pptxt As String = ""
        Dim TxtPath As String = ""
        Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
        If e.Action.ToString() = "ByMouse" Then '鼠标点击的时候，才进行展开操作，避免了初始化的情况
            Dim node As TreeNode = TreeView1.SelectedNode
            TxtPath = CodePath & Replace(node.FullPath, Split(node.FullPath, "\")(0), "") & ".txt"
            If IO.File.Exists(TxtPath) Then
                Label1.Visible = False
                Label1.Text = TxtPath
                RichTextBox1.Text = ReadTextFile(TxtPath)
            Else
                Label1.Visible = False
            End If
        End If

        '//展开节点
        If TreeView1.SelectedNode.ImageIndex <> 4 Then
            TreeView1.SelectedNode.Expand()
        End If
        PictureBox3.Visible = False
    End Sub
    Function ReadTextFile(ByVal FileName As String)
        '/读取txt文件，返回内容
        Dim TxtEncoderType As String = GetEncoder(FileName)
        Dim MyText As String
        Dim MyReader As StreamReader

        Select Case TxtEncoderType
            Case "UTF-8"
                MyReader = New StreamReader(FileName, Encoding.UTF8)
                MyText = MyReader.ReadToEnd()
                MyReader.Close()
            Case Else
                MyReader = New StreamReader(FileName, Encoding.Default)
                MyText = MyReader.ReadToEnd()
                MyReader.Close()
        End Select
        MyReader.Dispose()
        MyReader = Nothing
        Return MyText
    End Function

    Function GetEncoder(filename) As String
        '//判断文本文件的编码格式
        Dim fs As FileStream = File.OpenRead(filename)
        Dim cdet As Ude.CharsetDetector = New Ude.CharsetDetector()
        cdet.Feed(fs)
        cdet.DataEnd()
        fs.Close()
        Return cdet.Charset
    End Function

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        RefreshListbox1()
    End Sub

    Private Sub Code_Click(sender As Object, e As EventArgs) Handles Me.Click
        ListBox1.Visible = False
        PictureBox2.Visible = False
        PictureBox1.Visible = True
        PictureBox3.Visible = False
    End Sub


    Private Sub RichTextBox1_Click(sender As Object, e As EventArgs) Handles RichTextBox1.Click
        ListBox1.Visible = False
        PictureBox2.Visible = False
        PictureBox1.Visible = True
        PictureBox3.Visible = False
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If File.Exists(Label1.Text) Then
            'My.Computer.FileSystem.WriteAllText(Label1.Text, RichTextBox1.Text, False)
            Dim mStreamWriter As New System.IO.StreamWriter(Label1.Text, False)
            mStreamWriter.WriteLine(RichTextBox1.Text)
            mStreamWriter.Close()
            PictureBox3.Visible = True
        End If

    End Sub
    Function RefreshListbox1()
        If CheckBox1.Checked = False Then '深度查询需要查询代码内容。不只是标题。
            '/刷新Listbox1的列表
            ListBox1.Items.Clear()
            Dim arr1()
            Dim xx As Int16 = 0
            For X = 0 To UBound(arr, 2)
                If UCase(arr(1, X)) Like "*" & UCase(TextBox1.Text) & "*" Then
                    ReDim Preserve arr1(0 To xx)
                    arr1(xx) = arr(1, X)
                    xx = xx + 1
                End If
            Next
            If xx > 0 Then ListBox1.Items.AddRange(arr1)
        Else

            '/刷新Listbox1的列表
            ListBox1.Items.Clear()
            Dim arr1()
            Dim xx As Int16 = 0
            For X = 0 To UBound(arr, 2)
                If InStr(UCase(arr(2, X)), UCase(TextBox1.Text)) Or UCase(arr(1, X)) Like "*" & UCase(TextBox1.Text) & "*" Then
                    ReDim Preserve arr1(0 To xx)
                    arr1(xx) = arr(1, X)
                    xx = xx + 1
                End If
            Next
            If xx > 0 Then ListBox1.Items.AddRange(arr1)
        End If
    End Function

    Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
        If Not ListBox1.SelectedItem Is Nothing Then
            For i = 0 To UBound(arr, 2)
                If arr(1, i) = ListBox1.SelectedItem.ToString Then
                    Label1.Visible = False
                    Label1.Text = arr(0, i)
                    RichTextBox1.Text = arr(2, i)
                    '//设置关键字高亮
                    Dim strstart As Int16 = 0
                    Dim strend As Int16 = RichTextBox1.Text.Length

                    Dim Index As Int16 = RichTextBox1.Find(TextBox1.Text, strstart, strend, RichTextBoxFinds.None)
                    Do While Index <> -1
                        RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont, FontStyle.Bold)
                        RichTextBox1.SelectionColor = Color.Red
                        strstart = Index + TextBox1.Text.Length
                        Index = RichTextBox1.Find(TextBox1.Text, strstart, strend, RichTextBoxFinds.None)
                    Loop



                    '//
                End If
            Next
        End If
    End Sub

    Private Sub 复制全部ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 复制全部ToolStripMenuItem.Click
        Dim a As String = RichTextBox1.Text
        Clipboard.Clear()
        Clipboard.SetData(DataFormats.Text, a) '//复制RTF数据到剪贴板
    End Sub

    Private Sub 保存全部ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 保存全部ToolStripMenuItem.Click
        If File.Exists(Label1.Text) Then
            'My.Computer.FileSystem.WriteAllText(Label1.Text, RichTextBox1.Text, False)
            Dim mStreamWriter As New System.IO.StreamWriter(Label1.Text, False)
            mStreamWriter.WriteLine(RichTextBox1.Text)
            mStreamWriter.Close()
            PictureBox3.Visible = True
        End If

    End Sub

    Private Sub CodeFrom_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Call LoadForm()
    End Sub
    Function LoadForm()
        Dim RootNode As New TreeNode
        TreeView1.Nodes.Clear()
        'TreeView1.SelectedImageIndex = -1
        RootNode.ImageIndex = 0
        RootNode.SelectedImageIndex = RootNode.ImageIndex
        RootNode.Text = "VBA代码库"
        TreeView1.Nodes.Add(RootNode)
        Dim SonNode As TreeNode
        Dim GrandNode As TreeNode
        Dim node4 As TreeNode
        Dim k As Integer = 0
        '获取根目录下的文件夹
        Dim CodePath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\Code\"
        Dim dir As New IO.DirectoryInfo(CodePath)
        '/第一层文件夹
        For Each MyFol In dir.GetDirectories
            SonNode = New TreeNode
            SonNode.ImageIndex = 1
            SonNode.SelectedImageIndex = SonNode.ImageIndex
            SonNode.Text = MyFol.Name
            RootNode.Nodes.Add(SonNode)
            Dim dir2 As New IO.DirectoryInfo(MyFol.FullName)

            '/第二层文件夹
            For Each MyFol2 In dir2.GetDirectories
                GrandNode = New TreeNode
                GrandNode.ImageIndex = 1
                GrandNode.SelectedImageIndex = GrandNode.ImageIndex
                GrandNode.Text = MyFol2.Name
                SonNode.Nodes.Add(GrandNode)

                '/第二层文件
                For Each MyFile In IO.Directory.GetFiles(MyFol2.FullName)
                    Dim FileInfo As New IO.FileInfo(MyFile)
                    If FileInfo.Extension = ".txt" Then
                        node4 = New TreeNode
                        node4.ImageIndex = 4
                        node4.SelectedImageIndex = node4.ImageIndex
                        node4.Text = Replace(FileInfo.Name, ".txt", "")
                        GrandNode.Nodes.Add(node4)
                        '/代码信息写入数组
                        ReDim Preserve arr(0 To 2, 0 To k)
                        arr(0, k) = FileInfo.FullName
                        arr(1, k) = Replace(FileInfo.Name, ".txt", "")
                        arr(2, k) = ReadTextFile(FileInfo.FullName)
                        k = k + 1
                        '/
                    End If
                Next

            Next


            '/第一层文件
            For Each MyFile In IO.Directory.GetFiles(MyFol.FullName)
                Dim FileInfo As New IO.FileInfo(MyFile)
                If FileInfo.Extension = ".txt" Then
                    node4 = New TreeNode
                    node4.ImageIndex = 4
                    node4.SelectedImageIndex = node4.ImageIndex
                    node4.Text = Replace(FileInfo.Name, ".txt", "")
                    SonNode.Nodes.Add(node4)
                    '/代码信息写入数组
                    ReDim Preserve arr(0 To 2, 0 To k)
                    arr(0, k) = FileInfo.FullName
                    arr(1, k) = Replace(FileInfo.Name, ".txt", "")
                    arr(2, k) = ReadTextFile(FileInfo.FullName)
                    k = k + 1
                    '/
                End If
            Next

        Next
        TreeView1.Nodes(0).Expand()
        '//设置控件可见性
        PictureBox2.Visible = False
        ' TextBox1.Text = "      搜索"
        ListBox1.Visible = False
        Label1.Visible = False
        PictureBox3.Visible = False
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim p As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\Code\"
        Shell("explorer " & p, vbNormalFocus)
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        RefreshListbox1()
    End Sub

    Private Sub TreeView1_MouseDown(sender As Object, e As MouseEventArgs) Handles TreeView1.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then '目的是为了，鼠标右键的时候，直接进行选中节点。否则需要先选中，再右键
            TreeView1.SelectedNode = TreeView1.GetNodeAt(e.X, e.Y)
            Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
            Label1.Text = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & ".txt"
        End If
    End Sub

    Private Sub 重命名ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 重命名ToolStripMenuItem.Click
        If TreeView1.SelectedNode.Level > 0 Then
            TreeView1.SelectedNode.BeginEdit()
        Else
            MsgBox("根节点不支持重命名哦！")
        End If
    End Sub

    Private Sub TreeView1_AfterLabelEdit(sender As Object, e As NodeLabelEditEventArgs) Handles TreeView1.AfterLabelEdit
        '//重命名文件或者文件夹
        Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
        Dim TxtPath As String

        Try
            If Len(Trim(e.Label)) > 0 Then
                CodePath = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
                If TreeView1.SelectedNode.ImageIndex = 4 Then '根据ImageIndex来判断选择的节点类型,4的时候选择的是文件
                    TxtPath = CodePath & Replace(TreeView1.SelectedNode.Parent.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & "\" & e.Label & ".txt"
                    'FileSystem.Rename(Label1.Text, TxtPath)
                    My.Computer.FileSystem.RenameFile(Label1.Text, e.Label & ".txt")
                ElseIf TreeView1.SelectedNode.ImageIndex = 1 Then '选择的是文件夹
                    TxtPath = CodePath & Replace(TreeView1.SelectedNode.Parent.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & "\" & e.Label
                    Dim TxtPath2 As String = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "")
                    'FileSystem.Rename(TxtPath2, TxtPath)
                    My.Computer.FileSystem.RenameDirectory(TxtPath2, e.Label)
                End If
            End If
        Catch
            MsgBox(Err.Description)
        End Try
    End Sub

    Private Sub 新建文件夹ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 新建文件夹ToolStripMenuItem.Click
        '/第三层文件夹或者文本文件的下一集不支持新建节点
        If TreeView1.SelectedNode.Level = 2 Or TreeView1.SelectedNode.ImageIndex = 4 Then
            MsgBox("下一级不允许添加文件夹哦~")
            Exit Sub
        End If

        '//新建节点的功能
        Dim TxtPath As String
        Dim node As TreeNode
        Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
        If TreeView1.SelectedNode.ImageIndex = 1 Or TreeView1.SelectedNode.ImageIndex = 0 Then
            node = New TreeNode
            node.Text = "新建文件夹"
            node.ImageIndex = 1
            node.SelectedImageIndex = node.ImageIndex
            TreeView1.SelectedNode.Nodes.Add(node)
            TxtPath = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & "\" & "新建文件夹"
            IO.Directory.CreateDirectory(TxtPath)
        End If
    End Sub

    Private Sub 新建txtToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 新建txtToolStripMenuItem.Click
        If TreeView1.SelectedNode.Level = 0 Or TreeView1.SelectedNode.ImageIndex = 4 Or TreeView1.SelectedNode.Level = 3 Then
            MsgBox("这一级不允许添加txt哦~")
            Exit Sub
        End If

        Dim TxtPath As String
        Dim node As TreeNode
        Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
        If TreeView1.SelectedNode.ImageIndex = 1 Or TreeView1.SelectedNode.ImageIndex = 0 Then
            node = New TreeNode
            node.Text = "空文本文件"
            node.ImageIndex = 4
            node.SelectedImageIndex = node.ImageIndex
            TreeView1.SelectedNode.Nodes.Add(node)
            TxtPath = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & "\" & "空文本文件.txt"
            File.Create(TxtPath).Dispose()
        End If


    End Sub

    Private Sub 删除此项ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 删除此项ToolStripMenuItem.Click
        If TreeView1.SelectedNode.Level = 0 Then
            MsgBox("顶级目录不可删除~")
            Exit Sub
        End If
        Try
            Dim TxtPath As String
            Dim CodePath As String = Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\Code"
            If TreeView1.SelectedNode.ImageIndex = 4 Then '根据ImageIndex来判断选择的节点类型,4的时候选择的是文件
                TxtPath = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & ".txt"

                File.Delete(TxtPath)
                TreeView1.SelectedNode.Remove()
            ElseIf TreeView1.SelectedNode.ImageIndex = 1 Then '选择的是文件夹
                TxtPath = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "") & "\"
                Dim TxtPath2 As String = CodePath & Replace(TreeView1.SelectedNode.FullPath, Split(TreeView1.SelectedNode.FullPath, "\")(0), "")

                My.Computer.FileSystem.DeleteDirectory(TxtPath2, FileIO.DeleteDirectoryOption.DeleteAllContents)
                TreeView1.SelectedNode.Remove()
            End If

        Catch
            MsgBox(Err.Description)
        End Try

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim SelInfo As SelLineColInfo '申明自定数据类型
        SelInfo = VBGetSelection() '获取光标选中代码的位置信息
        _VBE.ActiveCodePane.CodeModule.InsertLines(SelInfo.SLine, RichTextBox1.Text)
    End Sub



    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Dim f1 As New 网络代码
        f1.Show()
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged

    End Sub
End Class